//
//  HotContentViewController.m
//  礼物说
//
//  Created by dllo on 16/4/25.
//  Copyright © 2016年 sunzhichao. All rights reserved.
//

#import "HotContentViewController.h"

#define kGIFTCONTENTURL [NSString stringWithFormat:@"http://api.liwushuo.com/v2/items/%@",num]

@interface HotContentViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UIWebViewDelegate>

@property (nonatomic, retain) BaseCollectionView *collectionView;
@property (nonatomic, retain) GiftContentModel *model;
@property (nonatomic, assign) NSInteger height;
@property (nonatomic, retain) BaseButton *likeButton;
@property (nonatomic, retain) BaseButton *buyButton;
@property (nonatomic, retain) UIWebView *webView;

@end

@implementation HotContentViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}

- (void)dealloc {
    [_judge release];
    [_giftNumber release];
    [_num release];
    [_buyButton release];
    [_likeButton release];
    [_collectionView release];
    [_model release];
    [_webView release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"礼物详情";
    self.view.backgroundColor = [UIColor whiteColor];
    self.tabBarController.tabBar.translucent = YES;
    self.tabBarController.tabBar.hidden = YES;
    // Do any additional setup after loading the view.
    [GiFHUD show];
    
    if ([_judge isEqualToString:@"收藏"]) {
        [self dataHandle:_giftNumber];
    }else{
        [self dataHandle:_num];
    }
    
}

#pragma mark - 创建Button
- (void) createButton {
    
    self.likeButton = [BaseButton buttonWithType:UIButtonTypeCustom];
    _likeButton.frame = CGRectMake(0, kHEIGHT - 40, kWIDTH / 2, kHEIGHTS(49));
    [self.view addSubview:_likeButton];
    [_likeButton setTitle:@"收藏" forState:UIControlStateNormal];
    [_likeButton addTarget:self action:@selector(likeButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_likeButton setImage:[UIImage imageNamed:@"xin2.png"] forState:UIControlStateNormal];
    _likeButton.userInteractionEnabled = YES;
    
    self.buyButton = [BaseButton buttonWithType: UIButtonTypeCustom];
    _buyButton.frame = CGRectMake(kWIDTH / 2, kHEIGHT - 40, kWIDTH / 2, kWIDTHS(49));
    [self.view addSubview:_buyButton];
    [_buyButton setTitle:@"上淘宝" forState:UIControlStateNormal];
    [_buyButton addTarget:self action:@selector(buyButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_buyButton setImage:[UIImage imageNamed:@"buy.png"] forState:UIControlStateNormal];
}

#pragma mark - 收藏
- (void)likeButtonAction:(UIButton *)button {
    
    NSArray *arr = [[DatabaseHandle shareDataBase] selectDataWithName:_model.name];
    if (arr.count == 0) {
        LiWu *liwu = [[[LiWu alloc] init] autorelease];
        liwu.name = _model.name;
        liwu.url = (NSString *)_num;
        NSString * str = _model.imgArr[0];
        liwu.pictrue = str;
        liwu.price = _model.price;
        
        [[DatabaseHandle shareDataBase] insertDataWithLiWu:liwu];
        [self createAlsert:@"提示" str1:@"收藏成功" back:NO];
    }
    [self createAlsert:@"提示" str1:@"已收藏" back:NO];
}

- (void)createAlsert:(NSString *)str str1:(NSString *)str1 back:(BOOL)back
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:str message:str1 preferredStyle: UIAlertControllerStyleAlert];
    [self presentViewController:alert animated:YES completion:nil];
    [UIView animateWithDuration:5 animations:^{
       [self dismissViewControllerAnimated:YES completion:^{
          if (back) {
                [self.navigationController popToRootViewControllerAnimated:YES];
            }
        }];
    }];
}

- (void)buyButtonAction:(UIButton *)button {
    BuyViewController *buyVc = [[BuyViewController alloc] init];
    [self.navigationController pushViewController:buyVc animated:YES];
    [buyVc release];
}

#pragma mark - 数据
- (void)dataHandle:(NSNumber *)num {
    [XRAFNetworkTool GETUrl:kGIFTCONTENTURL body:nil headFile:nil response:XRJSON success:^(NSURLSessionDataTask *task, id responseObject) {
        NSDictionary *data = responseObject[@"data"];
        self.model = [GiftContentModel modelWithDic:data];
        [self createButton];
        [self temp];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@", error);
    }];
}

- (void)temp {
    self.webView = [[[UIWebView alloc] initWithFrame:CGRectMake(0, 0, kWIDTH, 200)] autorelease];
    [_webView loadHTMLString:_model.detail_html baseURL:nil];
    _webView.delegate = self;
}

#pragma mark - 创建collectionView
- (void) createCollection {
    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumInteritemSpacing = 1;
    layout.minimumLineSpacing = 1;
    layout.itemSize = CGSizeMake(kWIDTH, kHEIGHT);
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    
    self.collectionView = [[BaseCollectionView alloc] initWithFrame:CGRectMake(0, 0, kWIDTH, kHEIGHT - 49) collectionViewLayout:layout];
//    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.pagingEnabled = NO;
    [self.view addSubview:_collectionView];
    [_collectionView release];
    [layout release];
    
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    
    [_collectionView registerClass:[GiftLunBoCollectionViewCell class] forCellWithReuseIdentifier:@"lunBoCell"];
    [_collectionView registerClass:[GiftContentCollectionViewCell class] forCellWithReuseIdentifier:@"contentCell"];
    [_collectionView registerClass:[GiftIntroduceCollectionViewCell class] forCellWithReuseIdentifier:@"introduceCell"];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 3;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        
        GiftLunBoCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"lunBoCell" forIndexPath:indexPath];
        cell.urlArr = _model.imgArr;
        return cell;
        
    }else if(indexPath.row == 1){
        
        GiftContentCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"contentCell" forIndexPath:indexPath];
        cell.model = _model;
        return cell;
        
    }else{
        
        GiftIntroduceCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"introduceCell" forIndexPath:indexPath];
        cell.model = _model;
        return cell;
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0) {
        return CGSizeMake(kWIDTH, kWIDTHS(300));
        
    }else if(indexPath.row == 1){
        
        //    文字的大小
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:17], NSFontAttributeName, nil];
        // 通过文字大小获取文本的高度
        CGRect rect = [_model.content boundingRectWithSize:CGSizeMake(kWIDTH, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        return CGSizeMake(kWIDTH, rect.size.height + kWIDTHS(80));
    } else {
#warning 高度未做自适应
        return CGSizeMake(kWIDTH, _height + kWIDTHS(50));
    }
}

#pragma mark - webView
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    CGFloat height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];
    CGRect frame = webView.frame;
    webView.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, height);
    
    NSLog(@"……%lf", webView.frame.size.height);
    self.height = webView.frame.size.height;
    
    [GiFHUD dismiss];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [self createCollection];
        
    });
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
